<?php


namespace app\index\controller;


use think\facade\Config;
use think\Request;

class Admin extends \Common{

    private $token = [];

    # 检验token
    public function __construct(Request $request = null){
        parent::__construct();
        if(\request()->action() == "info"){
            $arr = getallheaders();
            $token = $this->CheckToken(isset($arr["Authorization"]) ? $arr["Authorization"] : "");
            $this->token = $token;
        }
    }

    # 登录
    public function Login(){
        if(isset($_POST["username"]) && isset($_POST["password"])){
            $username = $_POST["username"]; $password = $_POST["password"];
            $admin = db("admin")->where("username", $username)->find();
            if(!empty($admin)){
                if($password == $admin["password"]){
                    $user = [
                        "aid" => $admin["aid"],
                        "time" => time()
                    ];
                    $data = [
                        "roles" => ["admin"],
                        "token" => $this->MakeToken($user)
                    ];
                    Code(200, false, $data);
                }else{
                    Code(403, "密码错误,请核对");
                }
            }else{
                Code(403, "账号不存在,请核对");
            }
        }else{
            Code(403, "服务器错误, 请稍后再试");
        }
    }

    # 注销
    public function Logout(){
        Code(200, false, "success");
    }

    # 获取基本信息
    public function Info(){
        $aid = $this->token["aid"];
        $admin = db("admin")->where("aid", $aid)->find();
        $data = [
            "avatar" => Config::get("app.ip")."static/image/admin.jpg",
            "name" => "管理员",
            "roles" => ["admin"],
            "username" => $admin["username"]
        ];
        Code(200, false, $data);
    }

}